<template>
  <div class="div-main">
    <!-- 面包导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 上方搜索框 -->
      <div class="search">
        <div>
          <span
            >部门
            <el-select
              clearable
              @change="searchUser"
              @clear="searchUser"
              size="mini"
              v-model="queryMap.departmentId"
              placeholder="请选择所属部门"
            >
              <el-option
                v-for="department in departments"
                :label="department.name"
                :key="department.id"
                :value="department.id"
              >
                <span style="float: left">{{ department.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">
                  <el-tag size="small" effect="plain" type="success">
                    {{ department.total }}人
                  </el-tag>
                </span>
              </el-option>
            </el-select>
          </span>
          <span
            >用户名
            <el-input
              clearable
              style="width: 180px"
              size="mini"
              placeholder="请输入用户名查询"
              v-model="queryMap.username"
            >
            </el-input>
          </span>
          <span
            >邮箱
            <el-input
              clearable
              style="width: 180px"
              size="mini"
              placeholder="请输入邮箱查询"
              v-model="queryMap.email"
            >
            </el-input>
          </span>
          <span
            >性别
            <el-radio v-model="queryMap.sex" label="1">帅哥</el-radio>
            <el-radio v-model="queryMap.sex" label="0">美女</el-radio>
            <el-radio v-model="queryMap.sex" label>全部</el-radio>
          </span>
        </div>
        <div>
          <span
            >昵称
            <el-input
              clearable
              style="width: 180px"
              size="mini"
              placeholder="请输入昵称查询"
              v-model="queryMap.nickname"
            ></el-input>
          </span>
          <el-button
            @click="reset"
            size="mini"
            icon="el-icon-refresh"
            style="margin-left: 50px"
            >重置</el-button
          >
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-search"
            @click="searchUser"
            >查询</el-button
          >
          <el-button
            size="mini"
            type="success"
            icon="el-icon-plus"
            @click="addDialogVisible = true"
            >添加</el-button
          >
          <el-button
            @click="excel"
            size="mini"
            v-hasPermission="'user:export'"
            icon="el-icon-download"
            >导出</el-button
          >
        </div>
      </div>
      <!-- 用户数据表格 -->
      <el-table :data="userList" max-height="400" border class="user-table">
        <el-table-column prop="id" label="#" width="60"> </el-table-column>
        <el-table-column prop="username" label="用户名" width="120">
        </el-table-column>
        <el-table-column prop="sex" label="性别" width="80">
          <el-tag type="success">{{
            (userList.sex = 1 ? "帅哥" : "美女")
          }}</el-tag>
        </el-table-column>
        <el-table-column
          prop="departmentId"
          sortable
          label="所属部门"
          width="160"
        ></el-table-column>
        <el-table-column
          prop="birth"
          sortable
          label="生日"
          width="160"
        ></el-table-column>
        <el-table-column prop="email" sortable label="邮箱"></el-table-column>
        <el-table-column
          prop="phoneNumber"
          label="电话"
          width="160"
        ></el-table-column>
        <el-table-column prop="isban" label="是否禁用" width="120">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              @change="changUserStatus(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              @click="handleClick(scope.row)"
              type="text"
              size="small"
            ></el-button>
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit-outline"
            ></el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
            ></el-button>
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="assignRoles(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pages">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryMap.pageNo"
          :page-sizes="[5, 10, 15, 400]"
          :page-size="100"
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <!-- 添加用户信息 -->
      <el-dialog
        title="添加用户"
        @close="closeDialog"
        :visible.sync="addDialogVisible"
        width="50%;"
      >
        <!-- 表单 -->
        <span>
          <el-form
            :model="addForm"
            :label-position="labelPosition"
            :rules="addFormRules"
            ref="addFormRef"
            label-width="80px"
          >
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="部门" prop="departmentId">
                    <el-select
                      v-model="addForm.departmentId"
                      placeholder="请选择所属部门"
                    >
                      <el-option
                        v-for="department in departments"
                        :key="department.id"
                        :label="department.name"
                        :value="department.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="addForm.nickname"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="addForm.sex">
                      <el-radio :label="1">帅哥</el-radio>
                      <el-radio :label="0">美女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>
            <el-form-item label="密码" prop="password">
              <el-input v-model="addForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="phoneNumber">
              <el-input v-model="addForm.phoneNumber"></el-input>
            </el-form-item>
            <el-form-item prop="birth" label="生日">
              <el-col :span="11">
                <el-date-picker
                  type="date"
                  value-format="yyyy年MM月dd日"
                  placeholder="选择出生日期"
                  v-model="addForm.birth"
                  style="width: 100%"
                ></el-date-picker>
              </el-col>
            </el-form-item>
          </el-form>
        </span>

        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="addUser"
            :loading="btnLoading"
            :disabled="btnDisabled"
            >确 定</el-button
          >
        </span>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog
        center
        title="分配角色"
        :visible.sync="assignDialogVisible"
        width="49%"
      >
        <span>
          <template>
            <el-transfer
              filterable
              :titles="['未拥有', '已拥有']"
              :button-texts="['到左边', '到右边']"
              v-model="value"
              :data="roles"
            ></el-transfer>
          </template>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="assignDialogVisible = false" class="el-icon-close"
            >取消分配</el-button
          >
          <el-button
            v-hasPermission="'user:assign'"
            type="primary"
            @click="doAssignRoles"
            class="el-icon-check"
            :loading="btnLoading"
            :disabled="btnDisabled"
            >确定分配</el-button
          >
        </span>
      </el-dialog>
      <!-- 修改用户信息 -->
      <el-dialog
        title="修改用户"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editClose"
      >
        <span>
          <el-form
            :model="editForm"
            :label-position="labelPosition"
            :rules="addFormRules"
            ref="editFormRef"
            label-width="80px"
          >
            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="用户名" prop="username">
                    <el-input
                      v-model="editForm.username"
                      :disabled="true"
                    ></el-input>
                    <el-input
                      type="hidden"
                      v-model="editForm.id"
                      :disabled="true"
                      style="display: none"
                    ></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="部门" prop="departmentId">
                    <el-select
                      v-model="editForm.departmentId"
                      placeholder="请选择所属部门"
                    >
                      <el-option
                        v-for="department in departments"
                        :key="department.id"
                        :label="department.name"
                        :value="department.id"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="10">
                <div class="grid-content bg-purple">
                  <el-form-item label="昵称" prop="nickname">
                    <el-input v-model="editForm.nickname"></el-input>
                  </el-form-item>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="grid-content bg-purple-light">
                  <el-form-item label="性别" prop="sex">
                    <el-radio-group v-model="editForm.sex">
                      <el-radio :label="1">帅哥</el-radio>
                      <el-radio :label="0">美女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </div>
              </el-col>
            </el-row>

            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <el-input v-model="editForm.phoneNumber"></el-input>
            </el-form-item>
            <el-form-item prop="birth" label="生日">
              <el-col :span="11">
                <el-date-picker
                  type="date"
                  value-format="yyyy年MM月dd日"
                  placeholder="选择出生日期"
                  v-model="editForm.birth"
                  style="width: 100%"
                ></el-date-picker>
              </el-col>
            </el-form-item>
          </el-form>
        </span>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="updateUser"
            :loading="btnLoading"
            :disabled="btnDisabled"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>


<script>
export default {
  name: "Users",
  data() {
    var checkEmail = (rule, value, callback) => {
      const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
      if (!value) {
        return callback(new Error("邮箱不能为空"));
      }
      setTimeout(() => {
        if (mailReg.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的邮箱格式"));
        }
      }, 100);
    };
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[34578]\d{9}$$/;
      if (!value) {
        return callback(new Error("电话号码不能为空"));
      }
      setTimeout(() => {
        // Number.isInteger是es6验证数字是否为整数的方法,实际输入的数字总是识别成字符串
        // 所以在前面加了一个+实现隐式转换

        if (!Number.isInteger(+value)) {
          callback(new Error("请输入数字值"));
        } else {
          if (phoneReg.test(value)) {
            callback();
          } else {
            callback(new Error("电话号码格式不正确"));
          }
        }
      }, 100);
    };
    return {
      btnLoading: false,
      btnDisabled: false,
      departments: [
        {id:1,name:"物资管理部"},
        {id:2,name:"采集部"},
        {id:3,name:"信息技术部"},
        {id:4,name:"行政部"},
        ],
      loading: true,
      total: 0,
      addDialogVisible: false, //添加对话框,
      editDialogVisible: false, //修改对话框
      assignDialogVisible: false, //分配角色对话框
      labelPosition: "right", //lable对齐方式
      //查询对象
      queryMap: {
        pageNum: 1,
        pageSize: 6,
        username: "",
        sex: "",
        nickname: "",
      },
      userList: [],
      addForm: {
        username: "",
        nickname: "",
        password: "",
        email: "",
        phoneNumber: "",
        sex: "",
        birth: "",
      }, //添加表单
      editForm: {}, //更新表单
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 3,
            max: 12,
            message: "长度在 3 到 12 个字符",
            trigger: "blur",
          },
        ],
        departmentId: [
          { required: true, message: "请选择部门", trigger: "blur" },
        ],
        sex: [{ required: true, message: "请选择性别", trigger: "blur" }],
        birth: [{ required: true, message: "请填写出生日期", trigger: "blur" }],
        email: [{ required: true, validator: checkEmail, trigger: "blur" }],
        phoneNumber: [
          {
            required: true,
            message: "请输入联系方式",
            validator: checkPhone,
            trigger: "blur",
          },
        ],
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
      }, //添加表单验证规则
      roles: [], //角色
      value: [], //用户拥有的角色
      uid: "",
    };
  },
  created() {
    this.getUserList();
    this.getDepartments();
    setTimeout(() => {
      this.loading = false;
    }, 500);
  },
  methods: {
    // 重置
    reset() {
      this.queryMap = {
        pageNum: 1,
        pageSize: 6,
        username: "",
        sex: "",
        nickname: "",
      };
    },
    // 获取用户列表
    async getUserList() {
      let { data: res } = await this.$http.get(
        "user/findUserList?pageNum=" +
          this.queryMap.pageNum +
          "&pageSize=" +
          this.queryMap.pageSize
      );
      if (res.code == 200) {
        console.log(res);
        this.total = res.data.total;
        this.userList = res.data.list;
      } else {
        this.$message.error(res.msg);
      }
    },
    // 导出excel表格
    excel() {
      window.location.href = "http://localhost:8080/XinGuan/user/excel";
    },
    // 获取部门信息
    async getDepartments() {
      // const { data: res } = await this.$http.get("department/findAll");
      // if (res.code !== 200) return this.$message.error("获取部门列表失败");
      // this.departments = res.data;
    },
    // 搜索用户
    searchUser() {
      this.queryMap.pageNum = 1;
      this.getUserList();
    },
    // 弹出用户分配角色
    async assignRoles(id) {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const { data: res } = await this.$http.get("user/" + id + "/roles");
      if (res.code == 200) {
        if (res.data.length == 0) {
          loading.close();
          return this.$message.error("用户不存在，请输入正确的id");
        }
        console.log(res);
        this.roles = res.data.roleName;
        this.value = res.data.remark;
        console.log(this.roles);
        console.log(this.value);
        this.uid = id;

        setTimeout(() => {
          loading.close();
          this.assignDialogVisible = true;
        }, 400);
      }
    },
    // 确定分配角色
    async doAssignRoles() {
      this.assignDialogVisible = true;
      this.btnLoading = true;
      this.btnDisabled = true;
      const { data: res } = await this.$http.post(
        "user/" + this.uid + "/assignRoles",
        this.value
      );
      if (res.code == 200) {
        console.log(res);
        this.$notify.success({
          title: "操作成功",
          message: "用户分配角色成功",
        });
      } else {
        this.$message.error("分配角色失败:" + res.msg);
      }
      this.assignDialogVisible = false;
      this.btnLoading = false;
      this.btnDisabled = false;
    },
    // 添加用户
    async addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return;
        } else {
          this.btnLoading = true;
          this.btnDisabled = true;
          const { data: res } = await this.$http.post("user/add", this.addForm);
          if (res.code == 200) {
            console.log(res);
            this.$notify.success({
              title: "操作成功",
              message: "用户添加成功",
            });
            this.addForm = {};
            this.getUserList();
            this.getDepartmets();
          } else {
            return this.$message.error("用户添加失败:" + res.msg);
          }
          this.addDialogVisible = false;
          this.btnLoading = false;
          this.btnDisabled = false;
        }
      });
    },
    handleSizeChange() {},
    handleCurrentChange() {},
    closeDialog() {},
  },
};
</script>

<style scoped>
.el-breadcrumb {
  font-size: 12px;
  padding-left: 10px;
  padding-bottom: 10px;
}

.search {
  display: flex;
  flex-direction: column;
  font-size: 14px;
}
.btn {
  margin: 0 15px;
}
.user-table {
  font-size: 10px;
  height: 400px;
}
.pages {
  margin: 10px;
}
.search div {
  margin-bottom: 10px;
}
.search span {
  margin: 15px;
}
</style>